<template>
  <div class="container">
    <div class="header">
      <div class="left-nav">全部直播</div>
      <div class="middle-search">
        <el-input
            placeholder="请输入搜索关键词"
            suffix-icon="el-icon-search"
            v-model="searchKeyword">
        </el-input>
      </div>
      <div class="right-operate" v-if="nowUser.role !== 0">
        <el-button type="primary" icon="el-icon-plus" size="small" v-if="nowUserStreamRoom === null"
                   @click="startCreateStream">创建直播
        </el-button>
        <el-button type="success" icon="el-icon-video-camera" size="small"
                   v-if="nowUserStreamRoom !== null && nowUserStreamRoom.status === 0" @click="updateStreamStatus(1)">
          开始直播
        </el-button>
        <el-button type="danger" icon="el-icon-video-camera" size="small"
                   v-if="nowUserStreamRoom !== null && nowUserStreamRoom.status === 1" @click="updateStreamStatus(0)">
          关闭直播
        </el-button>
        <el-button type="info" icon="el-icon-mobile-phone" size="small" v-if="nowUserStreamRoom !== null"
                   @click="startUpdateStream">我的直播间
        </el-button>
      </div>
    </div>
    <div class="main-box">
      <el-row :gutter="24">
        <el-col :span="6" v-for="(item,index) in streamRoomList" :key="index">
          <div class="single-stream-room" @click="jumpToSteamRoom(item)">
            <el-image :src="item.cover" alt="" class="stream-cover"></el-image>
            <div class="stream-info">
              <div class="stream-info-title">{{ item.title }}</div>
              <div class="stream-info-user">
                <el-avatar size="small"
                           :src="item.avatar"></el-avatar>
                <div class="stream-info-text">{{ item.username }}</div>
                <div class="stream-view-count">
                  直播间人数：{{ item.view }}
                  <el-tag effect="dark" type="success" size="mini" v-if="item.status === 1">直播中</el-tag>
                  <el-tag effect="dark" type="info" size="mini" v-if="item.status === 0">未开播</el-tag>
                </div>
              </div>
            </div>
          </div>
        </el-col>
      </el-row>
    </div>

    <el-dialog
        title="提示"
        :visible.sync="showStreamFormDialog"
        width="30%">
      <el-form ref="form" :model="streamForm" label-width="auto">
        <el-form-item label="直播标题">
          <el-input v-model="streamForm.title" placeholder="请输入直播标题"></el-input>
        </el-form-item>
        <el-form-item label="直播封面">
          <el-upload
              ref="coverUpload"
              :limit="1"
              :on-success="handleSuccess"
              :on-progress="handleProgress"
              :on-error="handleError"
              :show-file-list="false"
              drag
              action="https://yiyuy.mynatapp.cc/info/imageToOSS">
            <i class="el-icon-upload"></i>
            <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
          </el-upload>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="showStreamFormDialog = false">取 消</el-button>
        <el-button type="primary" @click="submitStreamInfo">{{ isAdd === true ? '提 交' : '更 新' }}</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>

import {
  addSteamInfo,
  getAllStreamRoom,
  getStreamRoomByUsername, updateRoomView,
  updateStreamRoomInfo,
} from "@/api/stream";
import {getUserInfo} from "@/api/login";

export default {
  name: 'LiveQA',
  data() {
    return {
      // 开启直播还是更新直播间信息
      isAdd: false,
      // 当前用户信息
      nowUser: {},
      streamRoomList: [],
      // 当前用户自己的直播间
      nowUserStreamRoom: null,
      searchKeyword: '',
      showStreamFormDialog: false,
      streamForm: {
        title: '',
        cover: '',
        roomId: '',
        status: '',
      }
    };
  },
  mounted() {
    this.getNowUserInfo();
    this.getStreamRoomList();
  },
  methods: {
    handleSuccess(response, file, fileList) {
      this.streamForm.cover = response.data;
      this.$message.success('文件上传成功')
    },
    // 图片上传中调用的函数
    handleProgress(event, files, fileList) {
      this.$message.warning('文件上传中...')
    },
    // 文件上传失败
    handleError(err, file, fileList) {
      this.$message.error('文件上传失败')
    },
    jumpToSteamRoom(item) {
      if (item.status === 0) {
        this.$message.warning('该直播间未开播')
        return
      }
      updateRoomView(item.roomId,0);
      this.$router.push({path: '/home/liveQADetail', query: {item: item, nowUser: this.nowUser}})
    },
    startCreateStream() {
      this.isAdd = true;
      this.showStreamFormDialog = true;
      this.$refs.coverUpload.clearFiles()
      this.streamForm = {
        title: '',
        cover: '',
        roomId: ''
      }
    },
    startUpdateStream() {
      this.isAdd = false;
      this.showStreamFormDialog = true;
      this.$refs.coverUpload.clearFiles()
      this.streamForm = this.nowUserStreamRoom
    },
    // 开启关闭直播
    updateStreamStatus(status) {
      this.streamForm = this.nowUserStreamRoom;
      this.streamForm.status = status;
      updateStreamRoomInfo(this.streamForm).then(res => {
        this.$message.success('操作成功')
        this.getStreamRoomList()
        this.getNowUserStreamRoom()
      })
    },
    // 获取当前用户信息
    getNowUserInfo() {
      getUserInfo().then(res => {
        this.nowUser = res.data
        // 如果用户不是患者 那就可以开直播 获取用户自己的直播间
        if (this.nowUser.role !== 0) {
          this.getNowUserStreamRoom();
        }
      })
    },
    // 获取全部直播间列表
    getStreamRoomList() {
      getAllStreamRoom().then(res => {
        this.streamRoomList = res.data
      })
    },
    // 获取当前用户直播间
    getNowUserStreamRoom() {
      getStreamRoomByUsername().then(res => {
        if (res.data !== null) {
          this.nowUserStreamRoom = res.data;
        }
      })
    },
    submitStreamInfo() {
      if (this.isAdd === true) {
        let roomId = Math.floor(Math.random() * 10000)
        this.streamForm.roomId = roomId
        addSteamInfo(this.streamForm).then(res => {
          this.$message.success(`创建直播成功，您的房间号为${roomId}`)
          this.showStreamFormDialog = false
          this.getNowUserStreamRoom();
          this.getStreamRoomList();
        })
      } else {
        updateStreamRoomInfo(this.nowUserStreamRoom).then(res => {
          this.$message.success('更新成功')
          this.showStreamFormDialog = false
          this.getNowUserStreamRoom();
          this.getStreamRoomList();
        })
      }
    }
  }
}
</script>

<style lang="less" scoped>
@keyframes MoveIn {
  0% {
    opacity: 0;
    transform: translateY(12px);
  }

  100% {
    opacity: 1;
    transform: translateY(0);
  }
}

.container {
  width: 100%;
  height: 100%;
  padding: 10px;
  display: flex;
  flex-direction: column;
  background-color: #f4f5f8;

  .header {
    display: flex;
    align-items: center;
    animation: MoveIn .7s cubic-bezier(.4, 0, .2, 1);

    .left-nav {
      font-size: 26px;
    }

    .middle-search {
      width: 30%;
      margin: 0 auto;

      /deep/ .el-input__inner {
        border-radius: 20px;
        background-color: hsl(0 0% 100% / .74);
        outline: transparent solid 2px;
        box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
      }
    }

    .right-operate {
      float: right;
    }
  }

  .main-box {
    width: 100%;
    flex: 1;
    overflow-y: auto;

    .single-stream-room {
      width: 100%;
      animation: MoveIn .7s cubic-bezier(.4, 0, .2, 1);
      background-color: #fff;
      border-radius: 6px;
      display: flex;
      flex-direction: column;
      cursor: pointer;
      box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
      margin-top: 15px;

      .stream-cover {
        width: 100%;
        height: 154px;
      }

      .stream-info {
        flex: 1;
        padding: 10px;

        .stream-info-title {
          font-size: 18px;
          white-space: nowrap; /* 确保文本在一行内显示 */
          overflow: hidden; /* 隐藏超出容器的文本 */
          text-overflow: ellipsis;
        }

        .stream-info-user {
          margin-top: 5px;
          display: flex;
          align-items: center;
          font-size: 14px;
          color: #999;

          .stream-info-text {
            margin-left: 5px;
          }

          .stream-view-count {
            margin-left: auto;
          }
        }
      }
    }
  }
}
</style>